package edu.pw.p2pclient.networking;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import android.util.Log;
import edu.pw.p2pclient.networking.messages.HelloMessage;
import edu.pw.p2pclient.networking.messages.MsgSerializer;

public class BroadcasterThread extends Thread {

	public static final long BROADCAST_FREQUENCY = 30000;
	public static final String TAG = "BroadcasterThread";
	private boolean mRunning = false;
	private DatagramSocket mSocket = null;
	private CommunicationService mCommService = null;

	public BroadcasterThread(DatagramSocket udpSocket) {

		super();
		mSocket = udpSocket;
		mCommService = CommunicationService.getInstance();
	}

	@Override
	public void run() {

		Thread.currentThread().setName(TAG);
		Log.i(TAG, "Starting broadcaster");
		mRunning = true;
		while (mRunning) {
			try {
				mSocket.setBroadcast(true);
				byte[] data = MsgSerializer.serialize(new HelloMessage(
						mCommService.getMyDeviceAddress()));
				DatagramPacket packet = new DatagramPacket(data, data.length,
						mCommService.getBroadcastAddress(),
						CommunicationService.DISCOVERY_PORT);
				Log.i(TAG, "Sending broadcast");
				mSocket.send(packet);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.e(TAG, "Hello packet cannot be sent.");
				e.printStackTrace();
			}
			if (!mRunning)
				break;
			try {
				Thread.sleep(BROADCAST_FREQUENCY);
			} catch (InterruptedException e) {
				Log.i(TAG, "Brodcaster interrupted. " + e.getMessage());
				mRunning = false;
			}
		}

		mSocket.close();

		mCommService.getHandler().sendMessage(
				android.os.Message.obtain(mCommService.getHandler(),
						CommunicationService.BROADCASTER_ENDED));
	}

	@Override
	public void interrupt() {

		Log.i(TAG, "Thread interrupted.");
		mRunning = false;
		mSocket.close();
		super.interrupt();
	}

}
